import React, { useState, useEffect } from 'react';
import { Button, Toast } from 'antd-mobile';
import { CheckCircleOutline } from 'antd-mobile-icons';
// @ts-ignore
import TimeRoller from 'react-timeroller';
import './remind.css';
import { NavBar } from 'antd-mobile';
import dayjs from 'dayjs';
import { reminderService, type ReminderItem } from '../../../utils/reminderService'; 

// 星期数据
const weekDays = [
  { label: '星期日', value: 0 },
  { label: '星期一', value: 1 },
  { label: '星期二', value: 2 },
  { label: '星期三', value: 3 },
  { label: '星期四', value: 4 },
  { label: '星期五', value: 5 },
  { label: '星期六', value: 6 },
];

// 时间段类型（英文标识）
type PeriodType = 'AM' | 'PM';

const Remind: React.FC = () => {
  // 初始状态：默认选中AM，时间8:00（24小时制为8）
  const [selectedDays, setSelectedDays] = useState<number[]>([]);
  const [hour24, setHour24] = useState(8); // 初始小时设为8（对应AM 8:00）
  const [minute, setMinute] = useState(0); // 初始分钟设为0
  const [currentPeriod, setCurrentPeriod] = useState<PeriodType>('AM'); // 初始时间段设为AM
  
  // 提醒相关状态
  const [reminders, setReminders] = useState<ReminderItem[]>([]);

  // 组件初始化时从全局服务加载提醒数据
  useEffect(() => {
    setReminders(reminderService.getReminders());
  }, []);

  // 切换星期选择
  const toggleDay = (day: number) => {
    setSelectedDays(prev =>
      prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day]
    );
  };

  // 切换AM/PM并调整对应时间
  const togglePeriod = (period: PeriodType) => {
    if (currentPeriod === period) return;
    
    setCurrentPeriod(period);
    
    // 切换时保持小时数但调整周期，同时保持分钟不变
    if (period === 'AM') {
      // 切换到AM时，如果当前小时大于12，则减去12
      setHour24(prev => prev >= 12 ? prev - 12 : prev);
    } else {
      // 切换到PM时，如果当前小时小于12，则加上12（12点特殊处理）
      setHour24(prev => prev !== 12 ? prev + 12 : prev);
    }
  };

  // 核心逻辑：监听24小时制时间变化，自动同步AM/PM
  // 规则：hour24 >= 12 → PM；hour24 < 12 → AM
  useEffect(() => {
    const newPeriod: PeriodType = hour24 >= 12 ? 'PM' : 'AM';
    if (newPeriod !== currentPeriod) {
      setCurrentPeriod(newPeriod);
    }
  }, [hour24, currentPeriod]);


  // 创建提醒逻辑
  const handleCreateReminder = () => {
    if (selectedDays.length === 0) {
      Toast.show({ content: '请至少选择一天', duration: 1500 });
      return;
    }
    
    // 创建新的提醒项
    const newReminder: ReminderItem = {
      id: Date.now().toString(),
      days: [...selectedDays],
      hour24,
      minute,
      period: currentPeriod,
      isActive: true,
      createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
    };
    
    // 使用全局服务添加提醒
    reminderService.addReminder(newReminder);
    
    // 更新本地状态
    setReminders(reminderService.getReminders());
    
    // 重新启动全局提醒检查
    reminderService.restartReminderCheck();
    
    // 转换为12小时制显示
    const hour12 = hour24 % 12 === 0 ? 12 : hour24 % 12;
    const formattedTime = `${hour12.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')} ${currentPeriod}`;
    
    Toast.show({
      content: (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <CheckCircleOutline style={{ color: '#00b42a', marginRight: 8 }} />
          <span>提醒创建成功，将在全局弹出</span>
        </div>
      ),
      duration: 2000,
    });
    
    console.log('创建提醒:', {
      days: selectedDays.map(day => weekDays[day].label),
      time: formattedTime,
      reminder: newReminder
    });
  };


  // 生成时间选项
  const generateMinuteOptions = () => Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0'));
  const generateHourOptions = () => Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0'));

  // 测试功能：设置一个即将到来的提醒（用于测试）
  const handleTestReminder = () => {
    const now = dayjs();
    const testTime = now.add(1, 'minute'); // 1分钟后提醒
    
    const testReminder: ReminderItem = {
      id: 'test_' + Date.now().toString(),
      days: [now.day()], // 今天
      hour24: testTime.hour(),
      minute: testTime.minute(),
      period: testTime.hour() >= 12 ? 'PM' : 'AM',
      isActive: true,
      createdAt: now.format('YYYY-MM-DD HH:mm:ss')
    };
    
    // 使用全局服务添加测试提醒
    reminderService.addReminder(testReminder);
    setReminders(reminderService.getReminders());
    reminderService.restartReminderCheck();
    
    Toast.show({
      content: `测试提醒已设置，将在 ${testTime.format('HH:mm')} 全局弹出`,
      duration: 3000,
    });
    
    console.log('设置测试提醒:', testReminder);
    console.log('调试信息:', reminderService.getDebugInfo());
  };

  // 显示调试信息
  const handleShowDebugInfo = () => {
    const debugInfo = reminderService.getDebugInfo();
    console.log('提醒服务调试信息:', debugInfo);
    
    Toast.show({
      content: `服务状态: ${debugInfo.isInitialized ? '已初始化' : '未初始化'}\n活跃提醒: ${debugInfo.activeReminders}\n定时器: ${debugInfo.hasInterval ? '运行中' : '已停止'}`,
      duration: 5000,
    });
  };

  // 快速测试功能：设置5秒后的提醒
  const handleQuickTest = () => {
    const now = dayjs();
    const testTime = now.add(5, 'seconds'); // 5秒后提醒
    
    const testReminder: ReminderItem = {
      id: 'quick_test_' + Date.now().toString(),
      days: [now.day()], // 今天
      hour24: testTime.hour(),
      minute: testTime.minute(),
      period: testTime.hour() >= 12 ? 'PM' : 'AM',
      isActive: true,
      createdAt: now.format('YYYY-MM-DD HH:mm:ss')
    };
    
    // 使用全局服务添加测试提醒
    reminderService.addReminder(testReminder);
    setReminders(reminderService.getReminders());
    reminderService.restartReminderCheck();
    
    Toast.show({
      content: `快速测试提醒已设置，将在5秒后弹出`,
      duration: 3000,
    });
    
    console.log('设置快速测试提醒:', testReminder);
  };

  // 精确测试功能：设置3秒后的提醒（验证3秒检测）
  const handlePreciseTest = () => {
    const now = dayjs();
    const testTime = now.add(3, 'seconds'); // 3秒后提醒
    
    const testReminder: ReminderItem = {
      id: 'precise_test_' + Date.now().toString(),
      days: [now.day()], // 今天
      hour24: testTime.hour(),
      minute: testTime.minute(),
      period: testTime.hour() >= 12 ? 'PM' : 'AM',
      isActive: true,
      createdAt: now.format('YYYY-MM-DD HH:mm:ss')
    };
    
    // 使用全局服务添加测试提醒
    reminderService.addReminder(testReminder);
    setReminders(reminderService.getReminders());
    reminderService.restartReminderCheck();
    
    Toast.show({
      content: `精确测试提醒已设置，将在3秒后弹出`,
      duration: 3000,
    });
    
    console.log('设置精确测试提醒:', testReminder);
  };

  return (
    <div className="remind-container">
        <NavBar className="nav" onBack={() => history.back()}>
      </NavBar>
      {/* 日期选择区 */}
      {/* 点击跳回我的页面 */}
    
      
      <div className="section">
        <div className="section-title">选择要锻炼的日期</div>
        <div className="day-selector">
          {weekDays.map(day => (
            <Button
              key={day.value}
              className={`day-btn ${selectedDays.includes(day.value) ? 'active' : ''}`}
              onClick={() => toggleDay(day.value)}
            >
              {day.label.slice(2)}
            </Button>
          ))}
        </div>
      </div>

      {/* 时间选择区 */}
      <div className="section">
        <div className="section-title">选择要锻炼的时间点</div>
        {/* AM/PM切换按钮（与时间选择器联动） */}
        <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', justifyContent: 'center' }}>
          <Button 
            size="small" 
            className={currentPeriod === 'AM' ? 'active period-btn' : 'period-btn'}
            onClick={() => togglePeriod('AM')}
          >
            AM
          </Button>
          <Button 
            size="small" 
            className={currentPeriod === 'PM' ? 'active period-btn' : 'period-btn'}
            onClick={() => togglePeriod('PM')}
          >
            PM
          </Button>
        </div>
        <div className="time-roller-wrapper">
          <div className="time-roller-container">
            {/* 小时选择器 */}
            <TimeRoller
              range={generateHourOptions()}
              selectedValue={hour24}
              setSelectedValue={setHour24}
              renderItem={(h: number) => {
                // 显示为12小时制+自动匹配的AM/PM
                const period = h >= 12 ? 'PM' : 'AM';
                const hour12 = h % 12 === 0 ? 12 : h % 12;
                return `${hour12} ${period}`;
              }}
              selectedItemStyle={{
                color: '#f56a00',
                fontWeight: 'bold',
                fontSize: '18px'
              }}
              itemHeight={36}
              visibleCount={5}
            />
            <span className="time-separator">:</span>
            {/* 分钟选择器 */}
            <TimeRoller
              range={generateMinuteOptions()}
              selectedValue={minute}
              setSelectedValue={setMinute}
              renderItem={(m: number) => m.toString().padStart(2, '0')}
              selectedItemStyle={{
                color: '#f56a00',
                fontWeight: 'bold',
                fontSize: '18px'
              }}
              itemHeight={36}
              visibleCount={5}
            />
          </div>
        </div>
      </div>

      {/* 提醒列表提示 */}
      {reminders.length > 0 && (
        <div className="section">
          <div className="section-title">已设置的提醒</div>
          <div className="reminder-tip">
            <div className="tip-content">
              <div className="tip-icon">🔔</div>
              <div className="tip-text">
                <div className="tip-title">提醒已设置完成</div>
                <div className="tip-desc">点击右上角的铃铛图标查看和管理所有提醒</div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 底部按钮区域 */}
      <div className="btn-container fixed-bottom">
        <div style={{ display: 'flex', gap: '6px', marginBottom: '12px', flexWrap: 'wrap' }}>
          <Button
            className="test-btn"
            onClick={handleTestReminder}
            size="small"
            color="warning"
          >
            测试提醒(1分钟后)
          </Button>
          <Button
            className="quick-test-btn"
            onClick={handleQuickTest}
            size="small"
            color="success"
          >
            快速测试(5秒)
          </Button>
          <Button
            className="precise-test-btn"
            onClick={handlePreciseTest}
            size="small"
            color="danger"
          >
            精确测试(3秒)
          </Button>
          <Button
            className="debug-btn"
            onClick={handleShowDebugInfo}
            size="small"
            color="primary"
          >
            调试信息
          </Button>
        </div>
        <Button
          className="create-btn"
          onClick={handleCreateReminder}
          size="large"
        >
          创建提醒
        </Button>
      </div>
    </div>
  );
};

export default Remind;
